package com.it.config;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.it.bean.Dict;
import com.it.bean.Menu;
import com.it.bean.Role;
import com.it.bean.User;
import com.it.mapper.*;
import com.it.utils.AppUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Component
@Profile({"dev"})
@RequiredArgsConstructor
public class DataInitialize implements CommandLineRunner {

    private final UserMapper userMapper;
    private final RoleMapper roleMapper;
    private final MenuMapper menuMapper;
    private final DictMapper dictMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void run(String... args) {
        if (userMapper.selectCount(null) == 0) {
            initUsers();
        }
        //initFlows();
        if (dictMapper.selectCount(null) == 0) {
            initDict();
        }
    }


    public void initUsers() {
        JSONObject userJson = JSONUtil.readJSONObject(new File("src/main/resources/static/initialize/user.json"), StandardCharsets.UTF_8);
        JSONObject roleJson = JSONUtil.readJSONObject(new File("src/main/resources/static/initialize/role.json"), StandardCharsets.UTF_8);
        JSONArray menuJsonArray = JSONUtil.readJSONArray(new File("src/main/resources/static/initialize/menu.json"), StandardCharsets.UTF_8);
        List<Menu> menus = JSONUtil.toList(menuJsonArray, Menu.class);
        Role role = JSONUtil.toBean(roleJson, Role.class);
        User user = JSONUtil.toBean(userJson, User.class);
        AppUtils.forSaveAudit(menus);
        AppUtils.forSaveAudit(role);
        AppUtils.forSaveAudit(user);
        userMapper.insert(user);
        roleMapper.insert(role);
        menuMapper.insertList(menus);
        //插入关联关系中间表
        userMapper.inertUserRole(user.getId(), role.getId());
        roleMapper.insertRoleMenu(role, menus);
    }

    public void initDict() {
        JSONArray dictJsonArray = JSONUtil.readJSONArray(new File("src/main/resources/static/initialize/dict.json"), StandardCharsets.UTF_8);
        List<Dict> ds = JSONUtil.toList(dictJsonArray, Dict.class);
        AppUtils.forSaveAudit(ds);
        dictMapper.insertList(ds);
    }
}
